package edu.upf.opencities.web.connector.impl;

import java.io.ByteArrayInputStream;
import java.io.InputStream;

import java.net.HttpURLConnection;
import java.net.URL;

import javax.xml.bind.JAXBContext;

import org.apache.log4j.Logger;

import edu.upf.opencities.web.connector.Connector;
import edu.upf.opencities.web.utils.Utils;

public class ConnectorURLImpl implements Connector {

	private static ConnectorURLImpl connector = null;
	public static Logger logger = Logger.getLogger(ConnectorImpl.class);

	public static synchronized ConnectorURLImpl getInstace() {
		if (null == connector) {
			connector = new ConnectorURLImpl();
		}
		return connector;
	}
	
	public Object executeURL(String command) {
		URL url;
		HttpURLConnection uc = null;
		Object returnObject = null;
		try {
			url = new URL(command.replace(" ", "%20"));
		if (logger.isTraceEnabled()) {
			logger.trace("Sending message to: " + url);
		}

		uc = (HttpURLConnection) url.openConnection();
		uc.setRequestMethod("GET");
		uc.setRequestProperty("Content-Type", "application/xml");
		uc.setRequestProperty("Accept", "application/xml");

		JAXBContext jc = JAXBContext.newInstance("edu.upf.opencities.datamodel");
		InputStream xml = uc.getInputStream();

		String xmlString = Utils.getInstance().inputStreamAsString(xml);
		returnObject =	jc.createUnmarshaller().unmarshal(new ByteArrayInputStream(xmlString.getBytes("UTF-8")));
		} catch (Exception e) {}
		uc.disconnect();
		return returnObject;
	}

}
